<template>
  <a-modal
    :visible="visible"
    :title="goods && goods.id ? '编辑商品' : '新增商品'"
    @ok="handleSubmit"
    @cancel="$emit('update:visible', false)"
    @visible-change="handleVisibleChange"
  >
    <a-form :model="form" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
      <a-form-item field="name" label="商品名称">
        <a-input v-model="form.name" placeholder="请输入商品名称" />
      </a-form-item>
      <a-form-item field="goodsNo" label="商品编号">
        <a-input v-model="form.goodsNo" placeholder="请输入商品编号" />
      </a-form-item>
      <a-form-item field="sellPrice" label="销售价">
        <a-input-number v-model="form.sellPrice" placeholder="请输入销售价" :min="0" />
      </a-form-item>
      <a-form-item field="marketPrice" label="市场价">
        <a-input-number v-model="form.marketPrice" placeholder="请输入市场价" :min="0" />
      </a-form-item>
      <a-form-item field="storeNums" label="库存">
        <a-input-number v-model="form.storeNums" placeholder="请输入库存数量" :min="0" />
      </a-form-item>
      <a-form-item field="status" label="状态">
        <a-radio-group v-model="form.status">
          <a-radio :value="true">上架</a-radio>
          <a-radio :value="false">下架</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { GoodsDetail } from '@/api/goods'

// 定义组件属性
const props = defineProps<{
  visible: boolean
  goods: GoodsDetail | null
}>()

// 定义组件事件
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'submit', form: GoodsDetail): void
}>()

// 处理对话框可见性变化
const handleVisibleChange = (val: boolean) => {
  emit('update:visible', val)
}

// 表单数据
const form = ref<GoodsDetail>({
  id: 0,
  name: '',
  goodsNo: '',
  sellPrice: 0,
  marketPrice: 0,
  costPrice: 0,
  storeNums: 0,
  status: true,
  img: '',
  content: ''
})

// 监听goods变化，更新表单数据
watch(
  () => props.goods,
  (newVal) => {
    if (newVal) {
      form.value = { ...newVal }
    } else {
      // 重置表单为默认值
      form.value = {
        id: 0,
        name: '',
        goodsNo: '',
        sellPrice: 0,
        marketPrice: 0,
        costPrice: 0,
        storeNums: 0,
        status: true,
        img: '',
        content: ''
      }
    }
  },
  { immediate: true, deep: true }
)

// 提交表单
const handleSubmit = () => {
  emit('submit', form.value)
}
</script>

<style scoped lang="less">
// 组件特定样式可以在这里添加
</style>
